/**
 * Filter 库
 * Created by hsu on 14-4-26.
 * version $Id: filters.js 3218 2014-05-22 06:26:13Z xuzhihui $
 */
(function (window, angular, undefined) {'use strict';
angular.module('kingFilters', [])
    //返回选定的记录
    .filter('slice',['$log', function($log){
        return function(array, page, limit){
//                $log.debug('>slice filter', array, page, limit);
            if (! angular.isArray(array) || array.length==0 || page<0 ){
                return array;
            }
            var out = [],
                offset = page*limit,
                end, i, n;
            // if abs(limit) exceeds maximum length, trim it
            end = offset + limit;
            if (end > array.length)
                end = array.length;
            else if (end < -array.length)
                end = -array.length;

            i = offset;
            if (end > 0) {
                n = end;
            } else {
                n = array.length + end;
            }

            for (; i<n; i++) {
                out.push(array[i]);
            }
            return out;
        }
    }])
    .filter('setPage', function(){
    	return function(array, vm, key){
    		if(key){
    			var keys = key.split('.');
    			var i = 0,
    				len = keys.length;
    			(function f(o, index){
    				
	    			if(index==len-1){
	    				o[keys[index]] = array.length;
	    				return;
	    			}	
	    			if(!o[keys[index]]) 
	    				o[keys[index]] = {};
	    			f(o[keys[index]], index+1)
    			})(vm, 0);
    			return array;
    		}
    		vm.totalSize = array.length;
    		return array;
    	}
    })
})(window, window.angular);